# -*- coding: utf-8 -*-
import os 
from os.path import join, getsize 
import pip
import requests
import json
# from bs4 import BeautifulSoup
# from tinydb import TinyDB, Query
from urllib.parse import quote, unquote
import feedparser
import time
from datetime import datetime
# from BeautifulSoup import BeautifulSoup
from tinydb import TinyDB, Query
from bs4 import BeautifulSoup
import pytz


class notification_Model:
    # 钉钉机器人的调用
    def dingdingTalk(self,msg):
        HEADERS = {"Content-Type": "application/json;charset=utf-8"}
        key = "e9b59afdcad471cd70b8e4016f2752a03084d66c34abea961f2ebf8a3d785a30"
        url = "https://oapi.dingtalk.com/robot/send?access_token=%s" % key
        data_info = {
            "msgtype": "text",
            "text": {
                # "content": "Log: \n" + msg
                "content": msg
            },
            "isAtAll": True
        }

        value = json.dumps(data_info)
        response = requests.post(url, data=value, headers=HEADERS)

    def notificationToken(self,titleMsg, message, regueURL):
        # tkoen = 'WwuUQD5ZNv7Aq9A67AswCN'#晓粉的
        tkoen = 'eJYzQEezv5JtJeR6mDQfVG'  # 我的
        first = quote(titleMsg, 'utf-8')
        second = quote(message, 'utf-8')
        
        # https://api.day.app/eJYzQEezv5JtJeR6mDQfVG/URL%20Test?url=https://www.baidu.com
        nowTmp = 'https://api.day.app/{}/{}/{}'.format(tkoen, first, second)
        if len(regueURL) != 0:
            third = quote(regueURL, 'utf-8')
            nowTmp = nowTmp + '?url=' + third
        res = requests.post(nowTmp)

        if res.json()['code'] == 200:
            print('发送成功')
        else:
            print(res.text)
    

class fuliba:  
    def netWork(self):
        url = 'https://fuliba2023.net/feed'
        feed = feedparser.parse(url)
        for entry in feed['entries']:
            # print(entry.keys())
            oneTime = entry['published']
            print(entry['published'] + '------' + entry['title'] + '------' + entry['link'])
            if self.transformTime(oneTime):
                print('1111111111111111')
                notification_Model.notificationToken(self=self,titleMsg=entry['title'],message='查看详情', regueURL=entry['link'])
            else:
                print('2222222222222222')

    def transformTime(self,oneTime):
        # Tue, 24 Oct 2023 10:49:53 +0000
        secondTime = time.strptime(oneTime.replace(' +0000', ''),'%a, %d %b %Y  %H:%M:%S')
        # print(secondTime.tm_year)

        nowtime = time.time()
        d = time.mktime(secondTime)
        # print(d)
        new = nowtime - d
        print(new)
        return new <= 3600        
    


class juejin:
    def loadData(self,uuid):
        urlValueJueJin ='https://api.juejin.cn/content_api/v1/article/query_list?aid=2608&uuid=7298633466618267190&spider=0'
        headers = {
            "content-type": "application/json",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
            "x-secsdk-csrf-token": "000100000001127b725792493486649386ff7e8a38df3e371049d8143a38417fbce498861e8f17806a861c68a960"
        }
        data = {"user_id":uuid,"sort_type":2,"cursor":"0"}
        respose = requests.post(url=urlValueJueJin,headers=headers,data=json.dumps(data).encode("utf-8"))
        resultData = respose.json()
        
        # print(resultData)
        if resultData['err_no'] == 0 and resultData['err_msg'] == 'success':
            firstData = resultData['data']
            # print(firstData)
            for item in firstData:
                itemID = item['article_id']
                titleValue = item['article_info']['title']
                brief_content = item['article_info']['brief_content']
                cover_image = item['article_info']['cover_image']
                ctime = item['article_info']['mtime']
                # print(self.transformTime2(item['article_info']['mtime']),'---',self.transformTime2(item['article_info']['ctime']))
                if ctime == None:
                    ctime = item['article_info']['ctime']
                createTime = self.transformTime(ctime)
                
                if createTime:
                    print(titleValue)
                    notification_Model.notificationToken(self=self,titleMsg=titleValue, message='查看详情',regueURL='https://juejin.cn/post/' + str(itemID))
        else:
            notification_Model.notificationToken(self=self,titleMsg='掘金', message='出现异常', regueURL="")

    def transformTime(self,timeString):
        py = pytz.timezone('Asia/Shanghai')
        old_time = datetime.fromtimestamp(float(timeString), py)
        now_time = datetime.now(py)
        totleTime = (now_time - old_time)
        stand_daysTime = totleTime.days
        stand_secondsTime = totleTime.seconds
        hoursTime = int(stand_secondsTime / 3600)
        minsTime = int((stand_secondsTime - hoursTime * 3600) / 60);
        secondsTime = (stand_secondsTime - hoursTime * 3600 - minsTime * 60);
        print(old_time, '----->',stand_daysTime, '---',stand_secondsTime, '---',hoursTime, '---',minsTime, '---',secondsTime)
        # print(old_time, '----->', stand_secondsTime, '----->', stand_daysTime)
        if stand_secondsTime <= 3600 and stand_daysTime == 0:
            print('--------->')
            return True
        else:
            return False
    
    def transformTime2(self,timeString):
        py = pytz.timezone('Asia/Shanghai')
        old_time = datetime.fromtimestamp(float(timeString), py)
        return old_time

        

class result_model:
    def total_func():
        fuliba().netWork()
        # now_time = datetime.now(pytz.timezone('Asia/Shanghai'))
        # print(now_time)
        arr_uuids = ['1574156384091320', '3483683111318823', '2946346894759319', '53218623894222','1139531179102392','1063982986187486','3298190611978526']
        for item in arr_uuids:
            juejin().loadData(item)       

def main_handler(event, context):
    result_model.total_func()
    
    
if __name__ == '__main__':
    result_model.total_func()